<?php

/**
 * @filename source_class.php 2013-11-11 02:10:56x
 * @author Huming Xu <huming17@126.com>
 * @version 1.0.0
 * @copyright DZF (c) 2013, Huming Xu
 */
if (!defined('IN_SITE')) {
    exit('Access Denied');
}

class trade_main {

    public $info_array = array();
    public $page_array = array();
    public $tree_array = array();
    public static $field_value = array();

    static function &instance() {
        static $object;
        if (empty($object)) {
            $object = new self();
        }
        return $object;
    }

    /*
     * 创建新订单
     */
    public function newTrade($cmIdArr = [], $user_id = 0, $trade_no = 0, $status = 'WAIT_BUYER_PAY', $time = 0, $pid = 0, $is_merge = 0, $is_free = 0, $isAdmin = false){
        if(!$cmIdArr || !$user_id || !$trade_no){//如果这三样不传递的话就无效
            return false;
        }
        
        if(!$time){
            $time = TIMESTAMP;
        }
        
        $trade_main['user_id'] = $user_id;
        $trade_main['tm_out_trade_no'] = $trade_no;
        $trade_main['tm_status'] = $status;
        //根据折扣 购买课程 计算总价
        $sql = "select sum(cm_price) from ".DB::table('course_main')." where cm_id IN (".dimplode($cmIdArr).") limit 1";
        $trade_main['tm_total_fee'] = $trade_main['tm_total_price'] = @DB::result_first($sql);
        $trade_main['tm_youhui'] = 0;

        $trade_main['pid'] = $pid;
        
        $trade_main['create_dateline'] = $time;
        
        if($is_free){//免费订单
            $trade_main['tm_youhui'] = $trade_main['tm_total_price'];
            $trade_main['tm_total_fee'] = 0;
            $trade_main['tm_all_status'] = 2;
            $trade_main['tm_paytime'] = TIMESTAMP;
        }
        
        if($isAdmin){//如果是后台添加的订单默认为已付款
            $trade_main['tm_all_status'] = 2;
            $trade_main['tm_paytime'] = TIMESTAMP;
        }
        
        if($is_merge){
            $trade_main['is_merge'] = 1;//标记此处为混合订单
        }
        else{
             $trade_main['so_id'] = $this->cmIdToSoId($cmIdArr[0]);//单一订单获取课程对应的网校
        }
        
        //把创建好的订单主键返回回去
        $tm_id = $this->add('trade_main', $trade_main, true);
        
        if(!$is_merge){//如果是一张混合订单的话只需要到这里，此时将生成的tm_id返回
            //如果不是一张混合订单的话此处需要将课程添加到订单课程表中去
            foreach($cmIdArr as $value){
                $course_main = $this->one_info('course_main', 'cm_id', $value);
                $data = [
                    'user_id'       => $user_id,
                    'cm_id'         => $value,
                    'group_cm_id'   => 0,
                    'cm_price'      => $course_main['cm_price'],
                    'tc_flag'       => 1,//2016-12-16 11:28:32 按照新的文档 1 表示未付款
                    'tc_type'       => 0,
                    'tm_id'         => $tm_id,
                    'create_dateline' => $time,
                    'modify_dateline' => $time,
                    'tc_applicant'  => 0,
                    'tc_take_handout' => 0
                ];

                if($is_free || $isAdmin){
                    $data['tc_flag'] = 2;
                }
                
                DB::insert('trade_course', $data, true);
            }

            $data = $trade_main;
            $data['tm_id'] = $tm_id;
            if($tm_id){
                //DEBUG 删除刚订单购物车数据 此处直接根据传参删除，不重复取数据库
                $condition = " user_id ='".$user_id."' and cm_id in (".  dimplode($cmIdArr).") ";
                @DB::delete('user_cart', $condition);
            }
            @DB::insert('trade_log', $data, true);
        }
        
        return $tm_id;
    }
    
    /*
     * 传入课程id获取对应的网校id
     */
    public function cmIdToSoId($cm_id = 0){
        if(!$cm_id){
            return false;
        }
        
        $sql_course_res = "select so_id "
                        . " from ".DB::table('course_main')." where cm_id = '".$cm_id."'";
        $courseRes = DB::fetch_first($sql_course_res);
        
        if(!empty($courseRes) && is_array($courseRes)){
            return $courseRes['so_id'];
        }
        
        return 0;
    }
    
    /*
     * 将指定订单纳入统计
     */
    public function toCourseStatistics($tm_id = 0){
        if(!$tm_id){
            return false;
        }
        //获取指定订单所有对应的课程订单数据
        $resArr = [];//定义接收结果池
        $sql_res = "select tc_id, user_id, cm_id, group_cm_id, cm_price, tm_id, tc_applicant "
                . " from ".DB::table('trade_course')." where isdelete = 0 and tc_flag = 2 and tc_type = 0 and tm_id = ".$tm_id;
        $resArr = DB::fetch_all($sql_res);

        if(!empty($resArr) && is_array($resArr)){
            foreach ($resArr as $item) {//遍历目标结果集重新组装数据
                // 目标数据格式
                // data['cs_cm_id'] //课程编号，关联pre_course_main.cm_id *
                // data['cs_user_id'] //用户编号，关联pre_user.user_id * 
                // data['cs_sm_id'] //学校编号，关联pre_school_main.sm_id *
                // data['cs_sm_type'] //学校类别，关联pre_school_main.sm_type，1：小学，2：初中，3：高中，4：一贯制 *
                // data['cs_class_id'] //班级编号，关联pre_class_main.class_id *
                // data['cs_am_id_1'] //地区编号，关联pre_area_main.am_id 省 *
                // data['cs_am_id_2'] //地区编号，关联pre_area_main.am_id 市 *
                // data['cs_am_id_3'] //地区编号，关联pre_area_main.am_id 县 *
                // data['cs_so_id'] //网校编号，关联pre_course_main.so_id *
                // data['cs_cm_price'] //收费额度，关联pre_course_main.cm_price *
                // data['cs_cm_cate_id'] //课程分类，关联pre_course_main.cm_cate_id *
                // data['cs_cm_grade_id'] //年级属性，关联pre_course_main.cm_grade_id *
                // data['cs_cm_subject_id'] //学科属性，关联pre_course_main.cm_subject_id *
                // data['cs_cm_cc_id_1_1'] //课程系统一级分类，关联pre_course_main *
                // data['cs_cm_cc_id_1_2'] //课程系统二级分类，关联pre_course_main *
                // data['cs_cm_cc_id_1_3'] //课程系统三级分类，关联pre_course_main *
                // data['cs_cm_cc_id_2_1'] //网校自建一级分类，关联pre_course_main *
                // data['cs_cm_cc_id_2_2'] //网校自建二级分类，关联pre_course_main *
                // data['cs_cm_cc_id_2_3'] //网校自建三级分类，关联pre_course_main *
                // data['cs_cm_cc_id_3_1'] //自定义自建一级分类，关联pre_course_main *
                // data['cs_cm_cc_id_3_2'] //自定义自建二级分类，关联pre_course_main *
                // data['cs_cm_cc_id_3_3'] //自定义自建三级分类，关联pre_course_main *
                // data['cs_tc_id'] //订单选课表主键，关联pre_trade_course.tc_id *
                // data['cs_group_cm_id'] //组合课程编号，关联pre_trade_course.group_cm_id *
                // data['cs_tm_id'] //订单表主键，关联pre_trade_course.tm_id *
                // data['cs_tc_applicant'] //选课申请人编号 0 表示选课人自己申请 关联pre_trade_course *
                // data['cs_tm_out_trade_no'] //网校订单号，关联pre_trade_main
                // data['cs_tm_trade_no'] //支付交易号
                // data['cs_tm_way'] //1 支付宝 2 人工收款 3 支付宝网银支付
                // data['cs_tm_bank_code'] //网银支付的银行简码
                // data['cs_is_free'] //是否免费订单：1.免费 0.非免费
                $data = [];
                //直接可获取部分
                $data['cs_cm_id'] = $item['cm_id'];
                $data['cs_tc_id'] = $item['tc_id'];
                $data['cs_user_id'] = $item['user_id'];
                $data['cs_group_cm_id'] = $item['group_cm_id'];
                $data['cs_cm_price'] = $item['cm_price'];
                $data['cs_tm_id'] = $item['tm_id'];
                $data['cs_tc_applicant'] = $item['tc_applicant'];
                //从课程表中查询出来的数据
                $sql_course_res = "select so_id, cm_price, cm_cate_id, cm_grade_id, cm_subject_id, cm_cc_id_1_1, cm_cc_id_1_2, cm_cc_id_1_3, cm_cc_id_2_1, cm_cc_id_2_2, cm_cc_id_2_3, cm_cc_id_3_1, cm_cc_id_3_2, cm_cc_id_3_3 "
                        . " from ".DB::table('course_main')." where cm_id = '".$item['cm_id']."'";
                $courseResArr = DB::fetch_first($sql_course_res);

                $data['cs_so_id'] = $courseResArr['so_id'];
                $data['cs_cm_price'] = $courseResArr['cm_price'];
                $data['cs_cm_cate_id'] = $courseResArr['cm_cate_id'];
                $data['cs_cm_grade_id'] = $courseResArr['cm_grade_id'];
                $data['cs_cm_subject_id'] = $courseResArr['cm_subject_id'];
                $data['cs_cm_cc_id_1_1'] = $courseResArr['cm_cc_id_1_1'];
                $data['cs_cm_cc_id_1_2'] = $courseResArr['cm_cc_id_1_2'];
                $data['cs_cm_cc_id_1_3'] = $courseResArr['cm_cc_id_1_3'];
                $data['cs_cm_cc_id_2_1'] = $courseResArr['cm_cc_id_2_1'];
                $data['cs_cm_cc_id_2_2'] = $courseResArr['cm_cc_id_2_2'];
                $data['cs_cm_cc_id_2_3'] = $courseResArr['cm_cc_id_2_3'];
                $data['cs_cm_cc_id_3_1'] = $courseResArr['cm_cc_id_3_1'];
                $data['cs_cm_cc_id_3_2'] = $courseResArr['cm_cc_id_3_2'];
                $data['cs_cm_cc_id_3_3'] = $courseResArr['cm_cc_id_3_3'];

                //从用户详情表中获取对应信息
                $sql_user_res = "select am_id_1, am_id_2, am_id_3, sm_id, class_id "
                        . " from ".DB::table('user_detail')." where user_id = '".$item['user_id']."'";
                $userResArr = DB::fetch_first($sql_user_res);

                $data['cs_am_id_1'] = $userResArr['am_id_1'];
                $data['cs_am_id_2'] = $userResArr['am_id_2'];
                $data['cs_am_id_3'] = $userResArr['am_id_3'];
                $data['cs_sm_id'] = $userResArr['sm_id'];
                $data['cs_class_id'] = $userResArr['class_id'];

                //从学校表中获取对应信息
                $sql_school_res = "select sm_type "
                        . " from ".DB::table('school_main')." where sm_id = '".$data['cs_sm_id']."'";
                $schoolResArr = DB::fetch_first($sql_school_res);

                $data['cs_sm_type'] = $schoolResArr['sm_type'];

                //从订单表中获取对应信息
                $sql_trade_res = "select tm_out_trade_no, tm_trade_no, tm_way, tm_bank_code, is_free "
                        . " from ".DB::table('trade_main')." where tm_id = '".$item['tm_id']."'";
                $tradeResArr = DB::fetch_first($sql_trade_res);

                $data['cs_tm_out_trade_no'] = $tradeResArr['tm_out_trade_no'];
                $data['cs_tm_trade_no'] = $tradeResArr['tm_trade_no'];
                $data['cs_tm_way'] = $tradeResArr['tm_way'];
                $data['cs_tm_bank_code'] = $tradeResArr['tm_bank_code'];
                $data['cs_is_free'] = $tradeResArr['is_free'];

                // data 数据入库
                $data['ctime'] = $data['mtime'] = TIMESTAMP;

                $this->add('course_statistics', $data);
            }
        }
    }
    
    /*
     * 	获取一条信息
     */

    public function one_info($table_name, $key_name, $key_id = '') {
        $info = array();
        if ($table_name && $key_name && $key_id) {
            $sql = "SELECT * FROM " . DB::table($table_name) . " WHERE " . $key_name . "='" . $key_id . "' LIMIT 1";
            $info = DB::fetch_first($sql);
        }
        return $info;
    }

    /*
     *  添加信息
     */

    public function add($table_name, $insert_data = array()) {
        $insert_id = '';
        if ($table_name && $insert_data) {
            $insert_id = DB::insert($table_name, $insert_data, true);
        }
        return $insert_id;
    }

    /*
     *  编辑信息
     */

    public function edit($table_name, $update_data, $where) {
        //DEBUG 定义返回 消息格式与消息代码编号
        $effect_row = '';
        if ($update_data && $where) {
            $effect_row = DB::update($table_name, $update_data, $where);
        }
        return $effect_row;
    }

    /*
     *  删除信息
     */

    public function delete($table_name, $where) {
        $return = '';
        if ($table_name && $where) {
            $return = DB::delete($table_name, $where, $limit = 1);
            //TODO 逻辑删需要创建isdelete字段 0=未删除 1=已删除
            //DB::update($table_name,array('isdelete'=>1), $table_name, $limit=1);
        }
        return $return;
    }

    /*
     *  列表信息
     *
     * @param $table_name string.
     * @param $page_condition array.
     *
     * @return array
     */

    public function index($table_name, $page_condition, $fields = '*') {
        $page_result = array();
        $page = $page_condition['page'];
        $limit = $page_condition['limit'];
        $perpage = $page_condition['perpage'];
        $start = (($page - 1) * $perpage);
        $wheresql = $page_condition['wheresql'];
        $orderby = $page_condition['orderby'];
        $sql_info = "SELECT " . $fields . " FROM " . DB::table($table_name) . " WHERE 1=1 " . $wheresql . " " . $page_condition['orderby'] . " " . DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        $sql_total_rows = "SELECT count(*) FROM " . DB::table($table_name) . " WHERE 1=1 " . $wheresql . "";
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        //DEBUG 列表数据返回结构
        $page_result = array(
            'page_now' => $page,
            'total_page' => max(1, ceil($sql_total_rows_result / $perpage)),
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $sql_info_result
        );
        return $page_result;
    }

    /**
     * 接口 AJAX或外部请求检索数据
     *
     * @param $table_name string.
     * @param $page_condition array.
     *
     * @return array
     */
    public function api($table_name, $page_condition) {
        $page_result = array();
        $page = $page_condition['page'];
        $limit = $page_condition['limit'];
        $perpage = $page_condition['perpage'];
        $start = (($page - 1) * $perpage);
        $wheresql = $page_condition['wheresql'];
        $orderby = $page_condition['orderby'];
        $sql_info = "SELECT * FROM " . DB::table($table_name) . " WHERE 1=1 " . $wheresql . " " . $page_condition['orderby'] . " " . DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        $sql_total_rows = "SELECT count(*) FROM " . DB::table($table_name) . " WHERE 1=1 " . $wheresql . "";
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        //DEBUG 列表数据返回结构
        $page_result = array(
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $sql_info_result
        );
        return $page_result;
    }

    /*
     *  获取表字段值
     * @param $table_name string
     * @param $key_name string
     * @param $key_id string/array
     * @param $field_name array
     *
     * @return $field_value array
     */

    protected static function get_field_value_by_id($table_name, $key_name, $key_id, $field_name='t.*') {
        if (is_array($key_id) && !empty($key_id)) {
            $key_ids = implode('_', $key_id);
            if (!isset(self::$field_value[$field_name . '_' . $key_ids])) {
                $limit = count($key_id);
                $return = DB::fetch_all('SELECT ' . $key_name . ',' . $field_name . ' FROM ' . DB::table($table_name) . " AS t WHERE " . $key_name . " IN (" . dimplode($key_id) . ") LIMIT " . $limit);
                foreach ($return AS $key => $value) {
                    $return_tmp[$value[$key_name]] = $value;
                    unset($return[$key]);
                }
                self::$field_value[$field_name . '_' . $key_ids] = $return_tmp;
                $key_id = $key_ids;
            } else {
                $key_id = $key_ids;
            }
        } else {
            if (!isset(self::$field_value[$field_name . '_' . $key_id])) {
                if (strpos($field_name, ",")) {
                    self::$field_value[$field_name . '_' . $key_id] = DB::fetch_first('SELECT ' . $key_name . ',' . $field_name . ' FROM ' . DB::table($table_name) . " AS t WHERE " . $key_name . "='" . $key_id . "' LIMIT 1");
                } else {
                    self::$field_value[$field_name . '_' . $key_id] = DB::result_first('SELECT ' . $key_name . ',' . $field_name . ' FROM ' . DB::table($table_name) . " AS t WHERE " . $key_name . "='" . $key_id . "' LIMIT 1");
                }
            }
        }
        return self::$field_value[$field_name . '_' . $key_id];
    }

    /*
     * ajax 返回信息
     */

    public function return_json($error, $message, $output = 1) {
        $return_array = array(
            "error" => $error,
            "message" => $message
        );
        if ($output) {
            echo json_ext($return_array);
            die;
        } else {
            return json_ext($return_array);
        }
    }

}

?>